package com.lopo.config;


import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.*;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import reactor.core.publisher.Mono;

import java.util.List;

public class MyLoadbalancer implements ReactorServiceInstanceLoadBalancer {
    private String ip;
    private DiscoveryClient discoveryClient;

    public MyLoadbalancer(String ip, DiscoveryClient discoveryClient) {
        this.ip = ip;
        this.discoveryClient = discoveryClient;
    }


    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        RequestDataContext context = (RequestDataContext) request.getContext();
        RequestData clientRequest = context.getClientRequest();
        String host = clientRequest.getUrl().getHost();
        List<ServiceInstance> instances = discoveryClient.getInstances(host);
        for (ServiceInstance instance : instances) {
            if (instance.getHost().equals(ip)) {
                return Mono.just(new DefaultResponse(instance));
            }
        }
        return Mono.just(new DefaultResponse(instances.get(0)));
    }
}
